import 'dart:convert';

/// 查询用户信息响应模型
class UserCheckResponse {
  final String status;
  final bool exists;
  final String message;
  final String accountType;
  final UserData? data;

  UserCheckResponse({
    required this.status,
    required this.exists,
    required this.message,
    required this.accountType,
    this.data,
  });

  /// 从JSON创建实例
  factory UserCheckResponse.fromJson(Map<String, dynamic> json) {
    return UserCheckResponse(
      status: json['status'] ?? '',
      exists: json['exists'] ?? false,
      message: json['message'] ?? '',
      accountType: json['account_type'] ?? '',
      data: json['data'] != null ? UserData.fromJson(json['data']) : null,
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'status': status,
      'exists': exists,
      'message': message,
      'account_type': accountType,
      if (data != null) 'data': data!.toJson(),
    };
  }

  /// 判断是否成功
  bool get isSuccess => status == 'success';

  @override
  String toString() {
    return 'UserCheckResponse{status: $status, exists: $exists, message: $message, accountType: $accountType, data: $data}';
  }
}

/// 用户数据模型
class UserData {
  final int userid;
  final String? userPhone;
  final String? userEmail;
  final int? userCode;
  final String? username;
  final String? userAvatarUrl;
  final Map<String, dynamic>? userData;
  final int? userAge;
  final String? userGender;
  final String? userSignature;
  final List<String>? userTags;
  final int? userLikes;
  final int? userFollowers;
  final int? userPoints;
  final List<String>? userHobbies;
  final String? userCity;
  final List<String>? userImgUrls;
  final String? userFrequentPlaces;
  final String? userBirthday;
  final int? userLevel;
  final String? status;
  final Map<String, dynamic>? extraData;
  final String? createdAt;
  final String? lastLogin;
  final String? updatedAt;

  UserData({
    required this.userid,
    this.userPhone,
    this.userEmail,
    this.userCode,
    this.username,
    this.userAvatarUrl,
    this.userData,
    this.userAge,
    this.userGender,
    this.userSignature,
    this.userTags,
    this.userLikes,
    this.userFollowers,
    this.userPoints,
    this.userHobbies,
    this.userCity,
    this.userImgUrls,
    this.userFrequentPlaces,
    this.userBirthday,
    this.userLevel,
    this.status,
    this.extraData,
    this.createdAt,
    this.lastLogin,
    this.updatedAt,
  });

  /// 从JSON创建实例
  factory UserData.fromJson(Map<String, dynamic> json) {
    return UserData(
      userid: json['userid'] ?? 0,
      userPhone: json['userPhone'],
      userEmail: json['userEmail'],
      userCode: json['userCode'],
      username: json['username'],
      userAvatarUrl: json['userAvatarUrl'],
      userData: _parseExtraData(json['userData']),
      userAge: json['userAge'],
      userGender: json['userGender'],
      userSignature: json['userSignature'],
      userTags: _parseStringList(json['userTags']),
      userLikes: json['userLikes'],
      userFollowers: json['userFollowers'],
      userPoints: json['userPoints'],
      userHobbies: _parseHobbies(json['userHobbies']),
      userCity: json['userCity'],
      userImgUrls: _parseStringList(json['userImgUrls']),
      userFrequentPlaces: json['userFrequentPlaces'],
      userBirthday: json['userBirthday'],
      userLevel: json['userLevel'],
      status: json['status'],
      extraData: _parseExtraData(json['extraData']),
      createdAt: json['created_at'],
      lastLogin: json['last_login'],
      updatedAt: json['updated_at'],
    );
  }

  /// 转换为JSON
  Map<String, dynamic> toJson() {
    return {
      'userid': userid,
      if (userPhone != null) 'userPhone': userPhone,
      if (userEmail != null) 'userEmail': userEmail,
      if (userCode != null) 'userCode': userCode,
      if (username != null) 'username': username,
      if (userAvatarUrl != null) 'userAvatarUrl': userAvatarUrl,
      if (userData != null) 'userData': userData,
      if (userAge != null) 'userAge': userAge,
      if (userGender != null) 'userGender': userGender,
      if (userSignature != null) 'userSignature': userSignature,
      if (userTags != null) 'userTags': userTags,
      if (userLikes != null) 'userLikes': userLikes,
      if (userFollowers != null) 'userFollowers': userFollowers,
      if (userPoints != null) 'userPoints': userPoints,
      if (userHobbies != null) 'userHobbies': userHobbies,
      if (userCity != null) 'userCity': userCity,
      if (userImgUrls != null) 'userImgUrls': userImgUrls,
      if (userFrequentPlaces != null) 'userFrequentPlaces': userFrequentPlaces,
      if (userBirthday != null) 'userBirthday': userBirthday,
      if (userLevel != null) 'userLevel': userLevel,
      if (status != null) 'status': status,
      if (extraData != null) 'extraData': extraData,
      if (createdAt != null) 'created_at': createdAt,
      if (lastLogin != null) 'last_login': lastLogin,
      if (updatedAt != null) 'updated_at': updatedAt,
    };
  }

  /// 获取融云Token
  String? get rongCloudToken {
    if (extraData != null && extraData!['token'] != null) {
      return extraData!['token'].toString();
    }
    return null;
  }

  /// 获取融云用户ID
  String? get rongCloudUserId {
    if (extraData != null && extraData!['rongcloud_user_id'] != null) {
      return extraData!['rongcloud_user_id'].toString();
    }
    return null;
  }

  /// 获取实名认证状态
  bool get isRealNameVerified {
    if (extraData != null) {
      return extraData!['real_name_verified'] == true ||
             extraData!['real_name_status'] == 'verified' ||
             extraData!['realNameStatus'] == 'verified';
    }
    return false;
  }

  /// 获取实名认证姓名
  String? get realName {
    if (extraData != null && extraData!['real_name'] != null) {
      return extraData!['real_name'].toString();
    }
    return null;
  }

  /// 获取实名认证身份证号（脱敏显示）
  String? get maskedIdCard {
    if (extraData != null && extraData!['id_card'] != null) {
      String idCard = extraData!['id_card'].toString();
      if (idCard.length >= 10) {
        return '${idCard.substring(0, 6)}****${idCard.substring(idCard.length - 4)}';
      }
      return idCard;
    }
    return null;
  }

  /// 获取实名认证时间
  String? get realNameVerifiedTime {
    if (extraData != null && extraData!['real_name_verified_time'] != null) {
      return extraData!['real_name_verified_time'].toString();
    }
    return null;
  }

  /// 解析字符串列表数据，处理JSON字符串转换
  static List<String>? _parseStringList(dynamic data) {
    if (data == null) return null;
    
    try {
      print('🔍 _parseStringList 输入数据: $data (类型: ${data.runtimeType})');
      
      if (data is List) {
        print('📋 处理List类型数据，长度: ${data.length}');
        List<String> result = [];
        
        for (var item in data) {
          print('  🔍 处理列表项: $item (类型: ${item.runtimeType})');
          
          if (item is String) {
            if (item.trim().isEmpty) continue;
            
            // 检查是否是JSON字符串数组
            if (item.startsWith('[') && item.endsWith(']')) {
              print('    🔧 检测到JSON字符串数组，尝试解析: $item');
              try {
                var decoded = json.decode(item);
                if (decoded is List) {
                  print('    ✅ JSON解析成功，添加${decoded.length}个项目');
                  for (var subItem in decoded) {
                    if (subItem != null && subItem.toString().isNotEmpty) {
                      result.add(subItem.toString());
                    }
                  }
                }
              } catch (e) {
                print('    ❌ JSON解析失败: $e');
                result.add(item);
              }
            } else {
              print('    ➕ 直接添加字符串: $item');
              result.add(item);
            }
          } else if (item != null) {
            print('    ➕ 转换为字符串添加: $item');
            result.add(item.toString());
          }
        }
        
        print('📋 List处理完成，结果: $result');
        return result.isNotEmpty ? result : null;
        
      } else if (data is String) {
        print('🔤 处理String类型数据: $data');
        if (data.trim().isEmpty) return null;
        
        // 尝试解析JSON字符串数组
        if (data.startsWith('[') && data.endsWith(']')) {
          print('  🔧 检测到JSON字符串，尝试解析');
          try {
            var decoded = json.decode(data);
            if (decoded is List) {
              List<String> result = List<String>.from(decoded.where((item) => item != null && item.toString().isNotEmpty));
              print('  ✅ JSON解析成功: $result');
              return result;
            }
          } catch (e) {
            print('  ❌ JSON字符串解析失败: $e, 原数据: $data');
            return [data];
          }
        } else {
          print('  ➕ 单个字符串: [$data]');
          return [data];
        }
      }
    } catch (e) {
      print('❌ 解析字符串列表数据出错: $e');
    }
    
    return null;
  }

  /// 解析extraData，处理JSON字符串转换
  static Map<String, dynamic>? _parseExtraData(dynamic data) {
    if (data == null) return null;
    
    try {
      if (data is Map<String, dynamic>) {
        return data;
      } else if (data is String) {
        if (data.trim().isEmpty) return null;
        
        // 尝试解析JSON字符串
        try {
          var decoded = json.decode(data);
          if (decoded is Map<String, dynamic>) {
            print('✅ extraData JSON解析成功: $decoded');
            return decoded;
          } else {
            print('⚠️ extraData解析结果不是Map: $decoded');
            return {'raw': data};
          }
        } catch (e) {
          print('❌ extraData JSON解析失败: $e, 原数据: $data');
          return {'raw': data};
        }
      }
    } catch (e) {
      print('❌ 解析extraData出错: $e');
    }
    
    return null;
  }

  /// 解析爱好数据，处理嵌套JSON字符串问题
  static List<String>? _parseHobbies(dynamic hobbiesData) {
    if (hobbiesData == null) return null;
    
    try {
      if (hobbiesData is List) {
        List<String> result = [];
        for (var item in hobbiesData) {
          if (item is String) {
            // 尝试解析嵌套的JSON字符串
            if (item.startsWith('[') && item.endsWith(']')) {
              try {
                // 解析JSON字符串
                var decoded = json.decode(item);
                if (decoded is List) {
                  for (var subItem in decoded) {
                    if (subItem is String && subItem.isNotEmpty && subItem != '[]') {
                      result.add(subItem);
                    }
                  }
                }
              } catch (e) {
                // 如果解析失败，直接添加原字符串（如果不是空数组字符串）
                if (item != '[]') {
                  result.add(item);
                }
              }
            } else if (item.isNotEmpty) {
              result.add(item);
            }
          }
        }
        return result.isNotEmpty ? result : null;
      } else if (hobbiesData is String) {
        if (hobbiesData.startsWith('[') && hobbiesData.endsWith(']')) {
          try {
            var decoded = json.decode(hobbiesData);
            if (decoded is List) {
              return List<String>.from(decoded.where((item) => item != null && item.toString().isNotEmpty));
            }
          } catch (e) {
            return [hobbiesData];
          }
        } else if (hobbiesData.isNotEmpty) {
          return [hobbiesData];
        }
      }
    } catch (e) {
      print('解析爱好数据出错: $e');
    }
    
    return null;
  }

  @override
  String toString() {
    return 'UserData{userid: $userid, userPhone: $userPhone, username: $username, userPoints: $userPoints, userLevel: $userLevel}';
  }
}
